<template>
  <div class="app-container" id="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
<!--      <el-form-item label="申请人用户ID" prop="userId">-->
<!--        <el-input-->
<!--          v-model="queryParams.userId"-->
<!--          placeholder="请输入申请人用户ID"-->
<!--          filterable clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="申请人部门ID" prop="deptId">-->
<!--        <el-input-->
<!--          v-model="queryParams.deptId"-->
<!--          placeholder="请输入申请人部门ID"-->
<!--          filterable clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="申请提交日期" prop="applyDate">
        <el-date-picker filterable clearable
                        v-model="queryParams.applyDate"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm"
                        placeholder="请选择申请提交日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="报销类型" prop="reimbursementType">
        <el-select v-model="queryParams.reimbursementType" placeholder="请选择报销类型" filterable clearable>
          <el-option
            v-for="dict in dict.type.oa_reimbursement_apply_reimbursement_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="总金额" prop="totalAmount">
        <el-input
          v-model="queryParams.totalAmount"
          placeholder="请输入总金额"
          filterable clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" filterable clearable>
          <el-option
            v-for="dict in dict.type.oa_reimbursement_apply_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- 更多查询条件-->
      <template v-if="isShowMore">


      </template>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button :icon="isShowMore?'el-icon-d-arrow-right':'el-icon-d-arrow-left'" size="mini" type="warning" @click="isShowMore = !isShowMore">更多查询</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['oa:reimbursement_apply:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['oa:reimbursement_apply:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['oa:reimbursement_apply:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['oa:reimbursement_apply:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-alert
      v-if="!isAdmin"
      title="仅显示您作为审批人或抄送人的报销申请"
      type="info"
      show-icon
      :closable="false"
      style="margin-bottom: 10px;"
    />

    <div class="apply-container">
      <!-- 普通用户：标签页 -->
      <template v-if="!isAdmin">
        <el-tabs v-model="activeTab" @tab-click="handleTabClick">
          <!-- 我的报销 -->
          <el-tab-pane label="报销记录" name="myApply">
            <el-table v-loading="loading" :data="myApplyList" stripe :height="tableHeight">
              <el-table-column type="index" width="55" label="序号" align="center" />
              <el-table-column label="申请提交日期" align="center" prop="applyDate" width="180">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.applyDate, '{y}-{m}-{d} {h}:{i}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="报销类型" align="center" prop="reimbursementType">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.oa_reimbursement_apply_reimbursement_type" :value="scope.row.reimbursementType"/>
                </template>
              </el-table-column>
              <el-table-column label="报销事由" align="center" prop="reason" />
              <el-table-column label="总金额" align="center" prop="totalAmount" />
              <el-table-column label="状态" align="center" prop="status">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.oa_reimbursement_apply_status" :value="scope.row.status"/>
                </template>
              </el-table-column>
              <el-table-column label="申请时间" align="center" width="180">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.applyTime, '{y}-{m}-{d} {h}:{i}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="180" fixed="right">
                <template #default="scope">
                  <el-button
                    v-if="scope.row.status === '待审批'"
                    size="mini"
                    type="text"
                    icon="el-icon-s-promotion"
                    @click="handleSubmit(scope.row)"
                    v-hasPermi="['oa:overtime:submit']"
                  >
                    发送
                  </el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-info"
                    @click="handleInfo(scope.row)"
                    v-hasPermi="['oa:overtime:query']"
                  >详情</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="handleUpdate(scope.row)"
                    v-hasPermi="['oa:overtime:edit']"
                  >修改</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row)"
                    v-hasPermi="['oa:overtime:remove']"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <!-- 审批记录 -->
          <el-tab-pane label="审批记录" name="approval">
            <el-table v-loading="loading" :data="approvalList" stripe :height="tableHeight">
              <el-table-column type="index" width="55" label="序号" align="center" fixed/>
              <el-table-column label="申请提交日期" align="center" prop="applyDate" width="180">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.applyDate, '{y}-{m}-{d} {h}:{i}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="报销类型" align="center" prop="reimbursementType">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.oa_reimbursement_apply_reimbursement_type" :value="scope.row.reimbursementType"/>
                </template>
              </el-table-column>
              <el-table-column label="报销事由" align="center" prop="reason" />
              <el-table-column label="总金额" align="center" prop="totalAmount" />
              <el-table-column label="状态" align="center" prop="status">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.oa_reimbursement_apply_status" :value="scope.row.status"/>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="150" fixed="right">
                <template #default="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-info"
                    @click="handleApprovalDetail(scope.row)"
                    v-hasPermi="['oa:overtime:approve']"
                  >处理</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <!-- 抄送记录 -->
          <el-tab-pane label="抄送记录" name="copied">
            <el-table v-loading="loading" :data="copiedList" stripe :height="tableHeight">
              <el-table-column type="index" width="55" label="序号" align="center" fixed/>
              <el-table-column label="申请提交日期" align="center" prop="applyDate" width="180">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.applyDate, '{y}-{m}-{d} {h}:{i}')}}</span>
                </template>
              </el-table-column>
              <el-table-column label="报销类型" align="center" prop="reimbursementType">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.oa_reimbursement_apply_reimbursement_type" :value="scope.row.reimbursementType"/>
                </template>
              </el-table-column>
              <el-table-column label="报销事由" align="center" prop="reason" />
              <el-table-column label="总金额" align="center" prop="totalAmount" />
              <el-table-column label="状态" align="center" prop="status">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.oa_reimbursement_apply_status" :value="scope.row.status"/>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="120" fixed="right">
                <template #default="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-info"
                    @click="handleInfo(scope.row)"
                  >查看</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </template>

      <!-- 管理员视图 -->
      <template v-else>
        <el-table v-loading="loading" :data="reimbursement_applyList" @selection-change="handleSelectionChange" stripe :height="tableHeight">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column type="index" width="55" label="序号" align="center" fixed/>
          <!--      <el-table-column label="主键ID" align="center" prop="id" />-->
          <!--      <el-table-column label="申请人用户ID" align="center" prop="userId" />-->
          <!--      <el-table-column label="申请人部门ID" align="center" prop="deptId" />-->
          <el-table-column label="申请提交日期" align="center" prop="applyDate" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.applyDate, '{y}-{m}-{d} {h}:{i}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="报销类型" align="center" prop="reimbursementType">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.oa_reimbursement_apply_reimbursement_type" :value="scope.row.reimbursementType"/>
            </template>
          </el-table-column>
          <el-table-column label="报销事由" align="center" prop="reason" />
          <el-table-column label="总金额" align="center" prop="totalAmount" />
          <!--      <el-table-column label="审批人ID" align="center" prop="approverIds" />-->
          <el-table-column label="审批人姓名" align="center" prop="approverNames" width="150"/>
          <!--      <el-table-column label="抄送人ID" align="center" prop="ccIds" />-->
          <el-table-column label="抄送人姓名" align="center" prop="ccNames" width="150"/>
          <el-table-column label="状态" align="center" prop="status">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.oa_reimbursement_apply_status" :value="scope.row.status"/>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180" fixed="right">
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.status === 'pending'"
                size="mini"
                type="text"
                icon="el-icon-s-promotion"
                @click="handleSubmit(scope.row)"
                v-hasPermi="['oa:overtime:submit']"
              >
                发送
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-info"
                @click="handleInfo(scope.row)"
                v-hasPermi="['oa:reimbursement_apply:query']"
              >详情</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['oa:reimbursement_apply:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['oa:reimbursement_apply:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>

    </div>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改OA报销申请主对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="68%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
<!--          <el-col :span="8">-->
<!--            <el-form-item label="申请人用户ID" prop="userId">-->
<!--              <el-input v-model="form.userId"  placeholder="请输入申请人用户ID" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="8">-->
<!--            <el-form-item label="申请人部门ID" prop="deptId">-->
<!--              <el-input v-model="form.deptId"  placeholder="请输入申请人部门ID" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="8">
            <el-form-item label="申请提交日期" prop="applyDate">
              <el-date-picker filterable clearable
                              v-model="form.applyDate"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm"
                              placeholder="请选择申请提交日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="报销类型" prop="reimbursementType">
              <el-select v-model="form.reimbursementType" placeholder="请选择报销类型">
                <el-option
                  v-for="dict in dict.type.oa_reimbursement_apply_reimbursement_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="报销事由" prop="reason">
              <el-input v-model="form.reason" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="总金额" prop="totalAmount">
              <el-input v-model="form.totalAmount"  placeholder="系统自动计算" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="审批人" prop="approverIds">
              <el-select
                v-model="form.approverIds"
                multiple
                filterable
                placeholder="请选择审批人"
                style="width: 100%"
              >
                <el-option
                  v-for="item in allEmpList"
                  :key="item.empId"
                  :label="item.empName"
                  :value="item.empId + ''"
                />
              </el-select>
            </el-form-item>
          </el-col>
<!--          <el-col :span="24">-->
<!--            <el-form-item label="审批人姓名" prop="approverNames">-->
<!--              <el-input v-model="form.approverNames" type="textarea" placeholder="请输入内容" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="24">
            <el-form-item label="抄送人" prop="ccIds">
              <el-select
                v-model="form.ccIds"
                multiple
                filterable
                placeholder="请选择抄送人"
                style="width: 100%"
              >
                <el-option
                  v-for="item in allEmpList"
                  :key="item.empId"
                  :label="item.empName"
                  :value="item.empId + ''"
                />
              </el-select>
            </el-form-item>
          </el-col>
<!--          <el-col :span="24">-->
<!--            <el-form-item label="抄送人姓名" prop="ccNames">-->
<!--              <el-input v-model="form.ccNames" type="textarea" placeholder="请输入内容" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="8">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态">
                <el-option
                  v-for="dict in dict.type.oa_reimbursement_apply_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
<!--          <el-col :span="8">-->
<!--            <el-form-item label="删除标记：0-正常，1-删除" prop="delFlag">-->
<!--              <el-input v-model="form.delFlag"  placeholder="请输入删除标记：0-正常，1-删除" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
        </el-row>
        <el-divider content-position="center">OA报销申请-费用明细信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddOaReimbursementDetail">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteOaReimbursementDetail">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="oaReimbursementDetailList" :row-class-name="rowOaReimbursementDetailIndex" @selection-change="handleOaReimbursementDetailSelectionChange" ref="oaReimbursementDetail" :height="tableHeight" >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="费用类型" prop="expenseType" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.expenseType" placeholder="请选择费用类型">
                <el-option
                  v-for="dict in dict.type.oa_reimbursement_detail_expense_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="费用发生时间" prop="occurrenceDate" width="240">
            <template slot-scope="scope">
              <el-date-picker filterable clearable v-model="scope.row.occurrenceDate" type="datetime" value-format="yyyy-MM-dd HH:mm" placeholder="请选择费用发生时间" />
            </template>
          </el-table-column>
          <el-table-column label="费用金额" prop="amount" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.amount" placeholder="请输入费用金额" />
            </template>
          </el-table-column>
          <el-table-column label="费用说明" prop="description" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.description" placeholder="请输入费用说明" />
            </template>
          </el-table-column>
          <el-table-column label="附件" prop="attachmentUrl" width="150">
            <template slot-scope="scope">
              <file-upload v-model="scope.row.attachmentUrl" placeholder="请输入附件" />
            </template>
          </el-table-column>
<!--          <el-table-column label="申请人ID" prop="userId" width="150">-->
<!--            <template slot-scope="scope">-->
<!--              <el-input v-model="scope.row.userId" placeholder="请输入申请人ID" />-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--          <el-table-column label="申请人部门ID" prop="deptId" width="150">-->
<!--            <template slot-scope="scope">-->
<!--              <el-input v-model="scope.row.deptId" placeholder="请输入申请人部门ID" />-->
<!--            </template>-->
<!--          </el-table-column>-->
        </el-table>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- OA报销申请主详情对话框 -->
    <el-dialog :title="title" :visible.sync="openInfo" width="68%" append-to-body>
      <el-descriptions border >
<!--        <el-descriptions-item label="申请人用户ID" >{{form.userId}}</el-descriptions-item>-->
<!--        <el-descriptions-item label="申请人部门ID" >{{form.deptId}}</el-descriptions-item>-->
        <el-descriptions-item label="申请提交日期" >
          {{ parseTime(form.applyDate, '{y}-{m}-{d} {h}:{i}')}}
        </el-descriptions-item>
        <el-descriptions-item label="报销类型" >
          <dict-tag :options="dict.type.oa_reimbursement_apply_reimbursement_type" :value="form.reimbursementType"/>
        </el-descriptions-item>
        <el-descriptions-item label="报销事由" >{{form.reason}}</el-descriptions-item>
        <el-descriptions-item label="总金额" >{{form.totalAmount}}</el-descriptions-item>
<!--        <el-descriptions-item label="审批人ID" >{{form.approverIds}}</el-descriptions-item>-->
        <el-descriptions-item label="审批人姓名" >{{form.approverNames}}</el-descriptions-item>
<!--        <el-descriptions-item label="抄送人ID" >{{form.ccIds}}</el-descriptions-item>-->
        <el-descriptions-item label="抄送人姓名" >{{form.ccNames}}</el-descriptions-item>
        <el-descriptions-item label="状态" >
          <dict-tag :options="dict.type.oa_reimbursement_apply_status" :value="form.status"/>
        </el-descriptions-item>
<!--        <el-descriptions-item label="删除标记：0-正常，1-删除" >{{form.delFlag}}</el-descriptions-item>-->
      </el-descriptions>
      <el-divider content-position="center">OA报销申请-费用明细信息</el-divider>
      <el-table :data="oaReimbursementDetailList" :row-class-name="rowOaReimbursementDetailIndex" @selection-change="handleOaReimbursementDetailSelectionChange" ref="oaReimbursementDetail">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="序号" align="center" prop="index" width="50"/>
        <el-table-column label="费用类型" prop="expenseType" width="150">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.oa_reimbursement_detail_expense_type" :value="scope.row.expenseType"/>
          </template>
        </el-table-column>
        <el-table-column label="费用发生时间" prop="occurrenceDate"  >
          <template slot-scope="scope">
            {{ parseTime(scope.row.occurrenceDate, '{y}-{m}-{d} {h}:{i}')}}
          </template>
        </el-table-column>
        <el-table-column label="费用金额" prop="amount" width="150" />
        <el-table-column label="费用说明" prop="description" width="150" />

        <el-table-column label="附件" width="180">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.attachmentUrl"
              type="primary"
              size="mini"
              @click="openFile(scope.row.attachmentUrl)"
            >
              查看
            </el-button>
            <span v-else>无</span>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listReimbursement_apply, getReimbursement_apply, delReimbursement_apply, addReimbursement_apply, updateReimbursement_apply, listApproval, listCopied, sendEmail } from "@/api/oa/reimbursement_apply";
import {listUser} from "@/api/system/user";


export default {
  name: "Reimbursement_apply",
  dicts: ['oa_reimbursement_apply_status', 'oa_reimbursement_detail_expense_type', 'oa_reimbursement_apply_reimbursement_type'],
  data() {
    return {
      activeTab: 'myApply',
      // 是否显示更多
      isShowMore: false,
      // el-table 高度
      loading: false,
      tableHeight: window.innerHeight - 200,
      // 普通用户各 Tab 数据
      myApplyList: [],
      approvalList: [],
      copiedList: [],
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedOaReimbursementDetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // OA报销申请主表格数据
      reimbursement_applyList: [],
      // OA报销申请-费用明细表格数据
      oaReimbursementDetailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详情弹出层
      openInfo: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        deptId: null,
        applyDate: null,
        reimbursementType: null,
        reason: null,
        totalAmount: null,
        approverIds: null,
        approverNames: null,
        ccIds: null,
        ccNames: null,
        status: null,
      },
      currentUserEmpName: this.$store.getters.nickName, // 获取当前登录用户名
      isAdmin: this.$store.getters.roles?.includes('admin') || false,
      // 表单参数
      form: {},
      allEmpList: [],
      empList: [],
      empMap: {},
      empLoading: false,
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "申请人用户ID不能为空", trigger: "blur" }
        ],
        deptId: [
          { required: true, message: "申请人部门ID不能为空", trigger: "blur" }
        ],
        applyDate: [
          { required: true, message: "申请提交日期不能为空", trigger: "blur" }
        ],
        reimbursementType: [
          { required: true, message: "报销类型不能为空", trigger: "change" }
        ],
        totalAmount: [
          { required: true, message: "总金额不能为空", trigger: "blur" }
        ],
        approverIds: [
          { required: true, message: "审批人ID不能为空", trigger: "blur" }
        ],
        approverNames: [
          { required: true, message: "审批人姓名不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.loadAllEmployees();
    this.getList();
    this.setTableHeight();
    window.addEventListener('resize', this.setTableHeight); // 监听窗口大小变化
    if (this.isAdmin) {
      this.loadAllApplications(); // 管理员加载全部数据
    } else {
      this.loadMyApplyList(); // 普通用户默认加载我的加班
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.setTableHeight); // 移除事件监听
  },
  watch: {
    oaReimbursementDetailList: {
      handler(newVal) {
        // 计算总金额
        let total = 0;
        if (Array.isArray(newVal)) {
          total = newVal
            .map(item => parseFloat(item.amount) || 0)
            .reduce((sum, val) => sum + val, 0);
        }
        // 保留两位小数（可选）
        this.form.totalAmount = total.toFixed(2);
      },
      deep: true // 深度监听，因为明细项内部属性会变
    }
  },
  methods: {
    loadAllEmployees() {
      listUser({}).then(res => {
        const users = res.rows || [];
        this.allEmpList = users.map(user => ({
          empId: user.userId,
          empName: user.nickName
        }));
        // 构建映射（用于显示姓名）
        users.forEach(user => {
          this.$set(this.empMap, user.userId, user.nickName);
        });
      }).catch(() => {
        this.$message.warning('加载员工列表失败');
      });
    },
    /** 提交申请（发送邮件给审批人和抄送人） */
    handleSubmit(row) {
      this.$confirm('确定要提交该报销申请吗？系统将自动发送邮件通知审批人与抄送人。', '提示', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        // 构造请求参数
        const params = {
          id: row.id,
          approverIds:row.approverIds,
          ccIds: row.ccIds,
          reimbursementType: row.reimbursementType,
          totalAmount: row.totalAmount,
          reason: row.reason,
          applicantName: this.$store.getters.nickName // 当前登录用户姓名
        };
        console.log('即将发送的参数:', params);
        console.log('approverIds 类型:', typeof params.approverIds); // 应该是 "string"
        console.log('approverIds 值:', params.approverIds);         // 应该是 "14" 或 "14,15"

        // 调用发送邮件接口
        this.loading = true;
        sendEmail(params)
          .then(res => {
            if (res && res.code === 200) {
              this.$message.success(res.msg || '提交成功');
            } else {
              this.$message.error(res?.msg || '提交失败');
            }
          })
          .catch(err => {
            console.error('邮件发送失败:', err);
            this.$message.error('网络错误，邮件发送失败！');
          })
          .finally(() => {
            this.loading = false;
          });
      }).catch(() => {
        this.$message.info('已取消提交');
      });
    },
    submitAndSend() {
      this.$refs["form"].validate(valid => {
        if (!valid) return;

        const approverIds = this.form.approverIds;
        const ccIds = this.form.ccIds;

        if (!approverIds || approverIds.length === 0) {
          this.$message.warning("请至少选择一位审批人");
          return;
        }

        const approverNames = approverIds.map(id => this.empMap[id]).filter(name => name).join('、');
        const ccNames = ccIds.map(id => this.empMap[id]).filter(name => name).join('、');

        const submitData = { ...this.form };
        submitData.approverIds = approverIds.join(',');
        submitData.ccIds = ccIds.join(',');
        submitData.approverNames = approverNames;
        submitData.ccNames = ccNames;

        // 如果是新增，则设置状态为“待审批”
        if (!this.form.applyId) {
          submitData.status = 'pending'; // 新增时自动设为待审批
        }

        const request = this.form.id ? updateReimbursement_apply(submitData) : addReimbursement_apply(submitData);
        this.loading = true;
        request.then(res => {
          if (res.code === 200) {
            this.$message.success("保存成功，正在发送邮件...");
            const emailParams = {
              id: res.data?.id || this.form.id,
              applicantName: this.currentUserEmpName,
              approverIds: submitData.approverIds,
              ccIds: submitData.ccIds,
              reimbursementType: row.reimbursementType,
              totalAmount: row.totalAmount,
              reason: submitData.reason
            };
            return sendEmail(emailParams).then(emailRes => {
              if (emailRes.code === 200) {
                this.$message.success("邮件已发送");
              } else {
                this.$message.warning("邮件发送失败: " + (emailRes.msg || '未知错误'));
              }
            });
          }
        }).then(() => {
          this.open = false;
          this.getList();
        }).catch(err => {
          console.error("提交或邮件发送失败:", err);
          this.$message.error("操作失败，请重试");
        }).finally(() => {
          this.loading = false;
        });
      });
    },
    handleTabClick(tab) {
      if (tab.name === 'myApply' && this.myApplyList.length === 0) {
        this.loadMyApplyList();
      } else if (tab.name === 'approval' && this.approvalList.length === 0) {
        this.loadApprovalList();
      } else if (tab.name === 'copied' && this.copiedList.length === 0) {
        this.loadCopiedList();
      }
    },

    // 普通用户：我的加班记录（我自己提交的）
    loadMyApplyList() {
      this.loading = true;
      const params = {
        applicantId: this.currentUserId,
        ...this.queryParams // ✅ 合并查询条件（如 startTime, durationDays 等）
      };
      listReimbursement_apply(params).then(res => {
        this.myApplyList = res.rows || [];
        this.total = res.total; // 用于分页组件
      }).catch(err => {
        this.$message.error('加载我的报销记录失败');
      }).finally(() => {
        this.loading = false;
      });
    },

    // 普通用户：我需要审批的
    loadApprovalList() {
      this.loading = true;
      // 后端支持查询：当前用户是审批人 的记录
      listApproval().then(res => {
        this.approvalList = res.rows || [];
      }).catch(err => {
        this.$message.error('加载审批记录失败');
      }).finally(() => {
        this.loading = false;
      });
    },

    // 普通用户：抄送给我的
    loadCopiedList() {
      this.loading = true;
      // 后端支持查询：当前用户在抄送人列表中
      listCopied().then(res => {
        this.copiedList = res.rows || [];
      }).catch(err => {
        this.$message.error('加载抄送记录失败');
      }).finally(() => {
        this.loading = false;
      });
    },

    // 管理员：加载所有报销记录（不加筛选条件）
    loadAllApplications() {
      this.loading = true;
      // 不传任何筛选条件 → 获取全部数据
      listReimbursement_apply({}).then(res => {
        this.applyList = res.rows || [];
      }).catch(err => {
        this.$message.error('加载全部报销记录失败');
      }).finally(() => {
        this.loading = false;
      });
    },

    openFile(attachmentUrl) {
      if (!attachmentUrl) {
        this.$message.warning('附件地址为空');
        return;
      }

      // 如果是相对路径，拼接 API 基础地址（根据你的项目配置）
      let fullUrl = attachmentUrl;
      if (!attachmentUrl.startsWith('http')) {
        // 假设你的后端文件服务和 API 同源，使用 VUE_APP_BASE_API（可在 .env 中配置）
        const baseUrl = process.env.VUE_APP_BASE_API || '';
        fullUrl = baseUrl.replace(/\/+$/, '') + '/' + attachmentUrl.replace(/^\/+/, '');
      }

      // 直接在新标签页打开（适用于公开可访问的文件）
      window.open(fullUrl, '_blank');
    },

    /** 查询OA报销申请主列表 */
    getList() {
      this.loading = true;
      // 构造请求参数
      const params = { ...this.queryParams };

      // 如果不是管理员，则只查询包含当前用户的记录（作为审批人或抄送人）
      if (!this.isAdmin) {
        params.includeMe = true; // 告诉后端：只返回当前用户是审批人或抄送人的记录
        params.currentUserName = this.currentUserEmpName; // 传当前用户名用于匹配
      }
      listReimbursement_apply(this.queryParams).then(response => {
        this.reimbursement_applyList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(() => {
        this.$message.error('加载报销申请列表失败');
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openInfo = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        deptId: null,
        applyDate: null,
        reimbursementType: null,
        reason: null,
        totalAmount: null,
        approverIds: null,
        approverNames: null,
        ccIds: null,
        ccNames: null,
        status: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null,
        delFlag: null
      };
      this.oaReimbursementDetailList = [];
      this.resetForm("form");
      this.empList = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if (this.isAdmin) {
        this.getList();
      } else {
        this.loadMyApplyList(); // ✅ 普通用户调用正确的加载方法
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.status = 'pending'; // 新增默认状态
      this.open = true;
      this.title = "添加OA报销申请主";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getReimbursement_apply(id).then(response => {
        // this.form = response.data;
        const data = response.data;
        // 1. 先复制数据
        this.form = { ...data };

        // 2. 将字符串转为数组（注意：split后是字符串数组，要转成数字或保持字符串）
        this.form.approverIds = data.approverIds ? data.approverIds.split(',').map(id => id.trim()) : [];
        this.form.ccIds = data.ccIds ? data.ccIds.split(',').map(id => id.trim()) : [];

        // 3. 加载溢选人员部分
        const selectedUserIds = [
          ...this.form.approverIds,
          ...this.form.ccIds
        ].map(id => parseInt(id)).filter(id => !isNaN(id));

        if (selectedUserIds.length > 0) {
          this.empLoading = true;
          listUser({ userIds: selectedUserIds }) // 查询用户信息
            .then(res => {
              const userData = Array.isArray(res?.rows) ? res.rows : [];
              this.empList = userData.map(u => ({
                empId: u.userId,
                empName: u.nickName
              }));

              // 构建 userId -> nickName 映射
              userData.forEach(u => {
                if (u?.userId && u?.nickName) {
                  this.$set(this.empMap, u.userId, u.nickName);
                }
              });

              this.empLoading = false;
            })
            .catch(err => {
              console.error('加载已选用户失败:', err);
              this.$message.warning('未能加载审批人/抄送人姓名');
              this.empLoading = false;
            });
        } else {
          this.empList = [];
        }
        this.oaReimbursementDetailList = response.data.oaReimbursementDetailList;
        this.open = true;
        this.title = "修改OA报销申请主";
      });
    },
    /** 详情按钮操作 */
    handleInfo(row) {
      this.reset();
      const id = row.id || this.ids
      getReimbursement_apply(id).then(response => {
        this.form = response.data;
        this.oaReimbursementDetailList = response.data.oaReimbursementDetailList;
        this.openInfo = true;
        this.title = "OA报销申请主详情";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) return;

        // ✅ 提取审批人和抄送人 ID
        const approverIds = this.form.approverIds || [];
        const ccIds = this.form.ccIds || [];

        // ✅ 获取对应的姓名（用于显示或存档）
        const approverNames = approverIds
          .map(id => this.empMap[id])
          .filter(name => name);
        const ccNames = ccIds
          .map(id => this.empMap[id])
          .filter(name => name);

        // ✅ 校验审批人有效性
        if (approverIds.length > 0 && approverNames.length === 0) {
          this.$message.warning('所选审批人未在系统中找到对应姓名，请重新选择');
          return;
        }

        // ✅ 处理明细列表：移除 id 字段，避免干扰后端自增逻辑
        const detailList = this.oaReimbursementDetailList.map(item => {
          const { id, ...rest } = item;
          return rest;
        });

        // ✅ 准备提交数据
        const submitData = { ...this.form };
        submitData.oaReimbursementDetailList = detailList;

        // ✅ 转换 ID 列表为逗号分隔字符串（兼容数据库字段）
        submitData.approverIds = approverIds.join(',');
        submitData.ccIds = ccIds.join(',');

        // ✅ 可选：保存姓名字段
        submitData.approverNames = approverNames.join(',');
        submitData.ccNames = ccNames.join(',');

        // ✅ 提交逻辑
        if (this.form.id != null) {
          updateReimbursement_apply(submitData).then(() => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
        } else {
          submitData.status = 'pending'; // 默认状态
          addReimbursement_apply(submitData).then(() => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除OA报销申请主编号为"' + ids + '"的数据项？').then(function() {
        return delReimbursement_apply(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** OA报销申请-费用明细序号 */
    rowOaReimbursementDetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** OA报销申请-费用明细添加按钮操作 */
    handleAddOaReimbursementDetail() {
      let obj = {};
      obj.expenseType = "";
      obj.occurrenceDate = "";
      obj.amount = "";
      obj.description = "";
      obj.attachmentUrl = "";
      obj.userId = "";
      obj.deptId = "";
      this.oaReimbursementDetailList.push(obj);
    },
    /** OA报销申请-费用明细删除按钮操作 */
    handleDeleteOaReimbursementDetail() {
      if (this.checkedOaReimbursementDetail.length == 0) {
        this.$modal.msgError("请先选择要删除的OA报销申请-费用明细数据");
      } else {
        const oaReimbursementDetailList = this.oaReimbursementDetailList;
        const checkedOaReimbursementDetail = this.checkedOaReimbursementDetail;
        this.oaReimbursementDetailList = oaReimbursementDetailList.filter(function(item) {
          return checkedOaReimbursementDetail.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleOaReimbursementDetailSelectionChange(selection) {
      this.checkedOaReimbursementDetail = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('oa/reimbursement_apply/export', {
        ...this.queryParams
      }, `OA报销申请主数据导出_${new Date().getTime()}.xlsx`)
    },
    // 设置表格高度
    setTableHeight() {
      const appContainer = document.getElementById('app-container');
      if (appContainer) {
        this.tableHeight = appContainer.clientHeight * 0.8;
      }
    }
  },
  mounted() {
    // 动态设置高度
    this.tableHeight = window.innerHeight - 200;
    window.onresize = () => {
      this.tableHeight = window.innerHeight - 200;
    };
  },
};
</script>
<style scoped>
.apply-container {
  padding: 16px;
  background-color: #fff;
}
.el-table {
  margin-top: 10px;
}
</style>
